%% Obtain Standard Errors of income parameters: Bootstrap
% Annika Bacher (annika.bacher@bi.no)
% following lecture notes of C. Tonetti
% May 2024

%% housekeeping
clear;
clc;
close all;

% !! ADD PATH TO WHERE EMPIRICAL RESULTS ARE STORED !!
datafolder = '...';


%% outer loop: seperately for male and female -- income: both labor and no asset income
  gender2 = [11 12 13 14];

for gender= gender2
    if gender == 11
 csvread([datafolder '/COVmale_coup_labinc.csv']);
     elseif gender == 12
 csvread([datafolder '/COVfemale_coup_labinc.csv']);
     elseif gender == 13
 csvread([datafolder '/COVmale_sing_labinc.csv']);
     elseif gender == 14
 csvread([datafolder '/COVfemale_sing_labinc.csv']);
    end

%% start bootstrapping procedure
rng default  

data = ans;
clear ans
data(data==0) = NaN;


R = 2000;        % number of replication draws
theta = 3;      % number of parameters to be estimated

mat= zeros(R,theta) ;

%%%%%%%%
% interpolate (linear) wages in missing years (bi-annuality of PSID)

P=19 ; % amount of waves available to study
T=29+1 ; % amout of calendar years the study covers + 1 for identifier

%%%%%%%%
% interpolate (linear) wages in missing years (bi-annuality of PSID after 1997)
data2= zeros(length(data),T) ;
data2(:,1)=data(:,1) ;

for i=2:9
data2(:,i)=data(:,i) ;   
end 

t=0;
for i = 10:2:T
    data2(:,i)=data(:,i-t) ;
    t=t+1;
end
clear t  

for j = 1: length(data)
for i = 11:2:(T-1)
    data2(j,i) = (data2(j,i-1)+data2(j,i+1))/2 ;
end
end

data= data2;
clear data2 
T=T-1;

%%%%%%%%

for i = 1:R
data2 = datasample(data,length(data)) ;
x= bootstrapSE(data2,gender) ;
mat(i,:) = x;
end

   se_rho    = sqrt(var(mat(:,1)));
   se_vare   = sqrt(var(mat(:,3)));
   se_vareta = sqrt(var(mat(:,2)));
   
   rho_BS    = mean(mat(:,1));
   vare_BS   = mean(mat(:,3));
   vareta_BS = mean(mat(:,2));
    
   
  if gender == 11
       save('male_coup_labinc','se_rho', 'se_vare', 'se_vareta','rho_BS','vare_BS','vareta_BS')
         elseif gender == 12
       save('female_coup_labinc','se_rho', 'se_vare', 'se_vareta','rho_BS','vare_BS','vareta_BS')
        elseif gender == 13
       save('male_sing_labinc','se_rho', 'se_vare', 'se_vareta','rho_BS','vare_BS','vareta_BS')
         elseif gender == 14
       save('female_sing_labinc','se_rho', 'se_vare', 'se_vareta','rho_BS','vare_BS','vareta_BS')
   end
end  